<?php

namespace app\common\model\service;

use app\common\model\BaseModel;
use app\common\model\hfztcy\LibMemberTeamChange;
use app\common\model\LibUser;
use common\Common;
use think\Db;
use think\Exception;

//公共函数

/**
 * 会员分销关系
 * @name LibMemberDistribute.php
 * @package hfztcy
 * @category model
 * @link http://www.chanekeji.com
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2022-06-17
 */
class LibMemberDistribute extends BaseModel
{
    public $openId;//扫码用户
    public $parentId;//推荐人

    public $model;
    public $userInfo = [];//扫码用户信息

    public $logPath;

    public function __construct($openId, $parentId)
    {
        $this->openId = $openId;
        $this->parentId = $parentId;
        $this->model = new LibUser();
        $userInfo = $this->model->findUser(['account' => $this->openId]);
        $this->userInfo = $userInfo['data'];
        $currentDate = date("Y-m-d",time());
        $this->logPath = ROOT_PATH . "public/subscribe/{$currentDate}";
        if (!is_dir($this->logPath)) mkdir($this->logPath,0777,true);
        parent::__construct();
    }

    /**
     * Info: 当前用户是否红娘
     * Date: 2022/11/28 10:46
     */
    private function _getIdentityByRedMother()
    {
        if ($this->userInfo && strpos($this->userInfo['identity'], '3') !== false) return true;
        return false;
    }

    /**
     * Info: 当前用户原先绑定的推荐人信息
     * Date: 2022/11/28 10:35
     */
    private function _getRedMotherIdentityByOriginalParentUser()
    {
        return $this->model->findUser(['id' => $this->userInfo['parent_id']]);
    }

    /**
     * Info: 当前用户扫描的二维码指定的推荐人信息
     * Date: 2022/11/28 10:35
     */
    private function _getRedMotherIdentityByQrCodeParentUser()
    {
        return $this->model->findUser(['id' => $this->parentId]);
    }

    /**
     * Info: 红娘团队信息
     * Date: 2022/11/28 10:47
     */
    private function _getMemberDistribute()
    {
        $sql = <<< SQL
    SELECT a.*
    FROM `hfztcy_member_distribute` a
    WHERE `a`.`user_id` = {$this->parentId}
SQL;
        file_put_contents($this->logPath.'/bind.log',$sql."\r\n",FILE_APPEND);
        return Db::query($sql);
    }

    /**
     * Info: 绑定用户
     * Date: 2022/11/28 10:47
     */
    public function bindUser()
    {
        if ($this->userInfo) {
            Db::startTrans();
            try {
                // 当前用户原先绑定的推荐人是否红娘身份
                $findParentUserRes = $this->_getRedMotherIdentityByOriginalParentUser();
                // 二维码指定的推荐人是否红娘身份
                $findQrCodeParentUserRes = $this->_getRedMotherIdentityByQrCodeParentUser();
                $update_user_flag = false;

                // 可以变动团队成员需满足的条件
                if (($findParentUserRes['errorCode'] == 1 || ($findParentUserRes['errorCode'] == 0 && (strpos($findParentUserRes['data']['identity'], '3') === false)))//原先绑定的上级用户身份不是红娘
                    && !$this->_getIdentityByRedMother()//当前扫码用户身份不是红娘
                    && ($findQrCodeParentUserRes['errorCode'] == 0 && (strpos($findQrCodeParentUserRes['data']['identity'], '3') !== false))) {//当前推荐人身份是红娘
                    $update_user_flag = true;
                }
                file_put_contents($this->logPath.'/bind.log','可以变动团队成员需满足的条件：'.($update_user_flag?1:0)."\r\n",FILE_APPEND);
                if ($update_user_flag) {
                    $old_parent_user_id = $this->userInfo['parent_id'];
                    // 记录团队变动
                    $data = [];
                    $data['user_id'] = $this->userInfo['id'];
                    $data['old_user_id'] = $old_parent_user_id;
                    $data['cur_user_id'] = $this->parentId;
                    $data['add_time'] = Common::getTime();
                    (new LibMemberTeamChange())->addMemberTeamChange($data);
                    // 更新`base_user`表字段 `parent_id`
                    $this->model->updateUser(['id' => $this->userInfo['id']], ['parent_id' => $this->parentId]);
                    file_put_contents($this->logPath.'/bind.log',$this->model->getLastSql()."\r\n",FILE_APPEND);
                    // 更新`hfztcy_member_distribute`表字段 `pid` `one_user_id` `two_user_id`
                    $distributeModel = new \app\common\model\hfztcy\LibMemberDistribute();
                    $findDistributeRes = $distributeModel->findMemberDistribute(['user_id' => $this->parentId]);
                    if ($findDistributeRes['errorCode'] == 1) {
                        $findUserRes = $this->model->findUser(['id' => $this->parentId]);
                        if ($findUserRes['errorCode'] == 1) {
                            $two_user_id = 0;
                        } else {
                            $two_user_id = $findUserRes['data']['parent_id'];
                        }
                        $distributeModel->addMemberDistribute([
                            'user_id' => $this->userInfo['id'],
                            'pid' => $this->parentId,
                            'one_user_id' => $this->parentId,
                            'two_user_id' => $two_user_id
                        ]);
                    } else {
                        $two_user_id = $findDistributeRes['data']['one_user_id'];
                    }
                    // 更新当前扫码用户上一级层级关系
                    $distributeModel->updateMemberDistribute(['user_id' => $this->userInfo['id']] , [
                        'pid' => $this->parentId,
                        'one_user_id' => $this->parentId,
                        'two_user_id' => $two_user_id
                    ]);
                    file_put_contents($this->logPath.'/bind.log','更新当前扫码用户上一级层级关系：'.$distributeModel->getLastSql()."\r\n",FILE_APPEND);
                    // 更新当前扫码用户上二级层级关系
                    $distributeModel->updateMemberDistribute(['one_user_id' => $this->userInfo['id']] , [
                        'two_user_id' => $this->parentId
                    ]);
                    file_put_contents($this->logPath.'/bind.log','更新当前扫码用户上二级层级关系：'.$distributeModel->getLastSql()."\r\n",FILE_APPEND);
                }

                // 不满足变更团队条件
                $this->_buildMemberTeam();

                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
            }
        }
    }

    /**
     * Info: 构建会员团队
     * Date: 2023/1/11 19:08
     */
    private function _buildMemberTeam()
    {
        $partnerDistributeModel = new \app\common\model\hfztcy\LibMemberDistribute();
        if ($this->parentId) {
            file_put_contents($this->logPath.'/bind.log',$this->parentId.'-'.$this->userInfo['id']."\r\n",FILE_APPEND);
            if ($this->parentId != $this->userInfo['id'])
            {
                $findDistributeRes = $partnerDistributeModel->findMemberDistribute(['user_id' => $this->userInfo['id']]);
                if ($findDistributeRes['errorCode'] == 0) {
                    //$partnerDistributeModel->updateMemberDistribute(['user_id' => $this->userInfo['id']], $user);
                } else {
                    $query = $this->_getMemberDistribute();
                    file_put_contents($this->logPath.'/bind.log',json_encode($query,JSON_UNESCAPED_UNICODE)."\r\n",FILE_APPEND);
                    $user = [];
                    $user['user_id'] = $this->userInfo['id'];//扫码用户ID
                    $user['pid'] = $this->parentId;//直接推荐人
                    if ($query) {
                        file_put_contents($this->logPath.'/bind.log',json_encode($query[0],JSON_UNESCAPED_UNICODE)."\r\n",FILE_APPEND);
                        $user['one_user_id'] = $this->parentId;//一级
                        $user['two_user_id'] = empty($query[0]['one_user_id']) ? 0 : $query[0]['one_user_id'];//二级
                    } else {
                        file_put_contents($this->logPath.'/bind.log',"无团队{$this->userInfo['id']}\r\n",FILE_APPEND);
                        $user['one_user_id'] = 0;
                        $user['two_user_id'] = 0;
                    }
                    $level = 0;
                    if ($user['one_user_id']) $level += 1;
                    if ($user['two_user_id']) $level += 1;
                    $user['use_level'] = $level;//层级
                    (new LibUser())->updateUser(array('open_id' => $this->openId), ['parent_id' => $this->parentId]);
                    $partnerDistributeModel->addMemberDistribute($user);
                    file_put_contents($this->logPath.'/bind.log',$partnerDistributeModel->getLastSql()."\r\n",FILE_APPEND);
                }
            } else {
                file_put_contents($this->logPath.'/bind.log',"不能自己绑定自己\r\n",FILE_APPEND);
            }
        } else {
            $user = [];
            $user['user_id'] = $this->userInfo['id'];//扫码用户ID
            $user['pid'] = $this->parentId;//直接推荐人
            $findDistributeRes = $partnerDistributeModel->findMemberDistribute(['user_id' => $this->userInfo['id']]);
            if ($findDistributeRes['errorCode'] == 0) {

            } else {
                $partnerDistributeModel->addMemberDistribute($user);
            }
        }
    }
}

?>